﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace Quan_ly_thong_tin_he_thong
{
    public partial class ThemPhongBan : Form
    {
        public ThemPhongBan()
        {
            InitializeComponent();
        }

        private void xoaThongTin()
        {
            MaSo_PB.Text = "";
            Ten_PB.Text = "";
        }

        private void xoaThongBao()
        {
            TenPBError.Text = "";
            MaPBError.Text = "";
        }

        private void insert_PhongBan(string MaSo_PB, string Ten_PB)
        {
            Config file = new Config(Application.StartupPath + "\\Config.ini");
            string connectionstring = file.ReadValue("server", "con");
            SqlConnection conn = new SqlConnection(connectionstring);
            string sql = "select * from PhongBan where MaSo_PB = @MaSo_PB";
            SqlCommand cmd = new SqlCommand(sql, conn);
            conn.Open();
            cmd.Parameters.AddWithValue("@MaSo_PB", MaSo_PB);
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                reader.Close();
                thongbaoLabel.Text = "Mã phòng ban này đã tồn tại !";
            }
            else
            {
                reader.Close();
                cmd.CommandText = "insert into PhongBan values(@MaSo_PB, @Ten_PB)";
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@MaSo_PB", MaSo_PB);
                cmd.Parameters.AddWithValue("@Ten_PB", Ten_PB);
                cmd.ExecuteNonQuery();
                thongbaoLabel.Text = "Thêm thành công";
            }
            conn.Close();
        }

        private void Them_Click(object sender, EventArgs e)
        {
            insert_PhongBan(MaSo_PB.Text, Ten_PB.Text);
            xoaThongTin();
        }

        private void quayLai_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void MaSo_PB_TextChanged(object sender, EventArgs e)
        {
            if(Regex.IsMatch(MaSo_PB.Text,"^[A-Za-z]{1,4}$"))
                MaPBError.Text="";
            else
                MaPBError.Text="*";

            if (MaSo_PB.Text.Length == 0)
                MaPBError.Text = "*";
        }
    }
}
